<template>
  <div class="job-fair-detail-page" v-loading="loading">
    <!-- 顶部封面和基本信息 -->
    <div class="banner-section" v-if="jobFair">
      <div class="banner-background" :style="{ backgroundImage: `url(${jobFair.poster})` }"></div>
      <div class="container">
        <div class="fair-basic-info">
          <div class="poster-container">
            <img :src="jobFair.poster" alt="招聘会海报" class="fair-poster">
            <div class="fair-badge" :class="getStatusClass(jobFair.status)">
              {{ getStatusText(jobFair.status) }}
            </div>
          </div>
          
          <div class="fair-info">
            <h1 class="fair-title">{{ jobFair.title }}</h1>
            
            <div class="fair-meta">
              <div class="meta-item">
                <el-icon><clock /></el-icon>
                <span>{{ jobFair.time }}</span>
              </div>
              <div class="meta-item">
                <el-icon><location /></el-icon>
                <span>{{ jobFair.location }}</span>
              </div>
              <div class="meta-item">
                <el-icon><office-building /></el-icon>
                <span>{{ jobFair.registeredCompanies || 0 }}家参会企业</span>
              </div>
              <div class="meta-item">
                <el-icon><user /></el-icon>
                <span>{{ jobFair.registeredUsers || 0 }}人已报名</span>
              </div>
            </div>
            
            <div class="fair-tags">
              <el-tag v-if="jobFair.type === 'online'" type="success" size="small">线上招聘会</el-tag>
              <el-tag v-else type="warning" size="small">线下招聘会</el-tag>
              <el-tag v-for="(tag, index) in jobFair.tags" :key="index" size="small">{{ tag }}</el-tag>
            </div>
            
            <div class="action-btns">
              <el-button 
                type="primary" 
                size="large" 
                :disabled="jobFair.status === 'ended' || ((userRole === 1 || userRole === '1') && companyRegistered) || isRegistered"
                :type="isRegistered ? 'success' : 'primary'"
                @click="handleRegister"
              >
                {{ getActionButtonText(jobFair.status, isRegistered) }}
              </el-button>
              
              <el-button 
                type="success" 
                size="large" 
                :icon="Share"
                @click="showShareDialog"
              >
                分享
              </el-button>
              
              <el-button 
                v-if="jobFair.type === 'offline'" 
                size="large" 
                :icon="Position"
                @click="showLocationMap"
              >
                查看地图
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="container main-content" v-if="jobFair">
      <!-- 导航标签 -->
      <el-tabs v-model="activeTab" class="fair-tabs">
        <el-tab-pane label="招聘会介绍" name="introduction">
          <div class="fair-introduction">
            <h2 class="section-title">招聘会介绍</h2>
            
            <div class="introduction-content">
              <div v-html="jobFair.description" class="rich-text"></div>
            </div>
            
            <div class="fair-highlights" v-if="jobFair.highlights && jobFair.highlights.length">
              <h3 class="subsection-title">招聘会亮点</h3>
              <div class="highlights-list">
                <div v-for="(highlight, index) in jobFair.highlights" :key="index" class="highlight-item">
                  <el-icon class="highlight-icon"><check /></el-icon>
                  <div class="highlight-text">{{ highlight }}</div>
                </div>
              </div>
            </div>
            
            <div class="fair-requirements" v-if="jobFair.requirements">
              <h3 class="subsection-title">参会须知</h3>
              <div v-html="jobFair.requirements" class="rich-text"></div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="参会企业" name="companies">
          <div class="participating-companies">
            <h2 class="section-title">参会企业</h2>
            
            <div class="company-search">
              <el-input
                v-model="companyKeyword"
                placeholder="搜索企业名称"
                prefix-icon="search"
                clearable
              ></el-input>
            </div>
            
            <div class="company-list" v-if="filteredCompanies.length">
              <div 
                v-for="company in filteredCompanies" 
                :key="company.id" 
                class="company-card"
                @click="viewCompanyDetail(company.id)"
              >
                <div class="company-logo">
                  <img v-if="company.logo" :src="company.logo" :alt="company.name">
                  <div class="logo-placeholder" v-else>{{ company.name.substring(0, 1) }}</div>
                </div>
                
                <div class="company-info">
                  <h3 class="company-name">{{ company.name }}</h3>
                  <div class="company-industry">{{ company.industry }}</div>
                  <div class="company-meta">
                    <span>{{ company.size }}</span>
                    <span>{{ company.location }}</span>
                  </div>
                 
                </div>
                
                <div class="company-actions">
                  <el-button type="primary" size="small" @click.stop="viewCompanyJobs(company.id)">
                    查看职位
                  </el-button>
                </div>
              </div>
            </div>
            
            <el-empty v-else description="暂无符合条件的企业" />
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="招聘职位" name="jobs">
          <div class="job-positions">
            <h2 class="section-title">招聘职位</h2>
            
            <div class="job-filter">
              <el-input
                v-model="jobKeyword"
                placeholder="搜索职位名称或关键词"
                class="job-search"
                prefix-icon="search"
                clearable
              ></el-input>
              
              <div class="filter-options">
                <el-select
                  v-model="jobFilters.industry"
                  placeholder="所属行业"
                  clearable
                >
                  <el-option
                    v-for="item in industryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
                
                <el-select
                  v-model="jobFilters.experience"
                  placeholder="经验要求"
                  clearable
                >
                  <el-option
                    v-for="item in experienceOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
                
                <el-select
                  v-model="jobFilters.education"
                  placeholder="学历要求"
                  clearable
                >
                  <el-option
                    v-for="item in educationOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </div>
            </div>
            
            <div class="job-list" v-if="filteredJobs.length">
              <div 
                v-for="job in filteredJobs" 
                :key="job.id" 
                class="job-card"
                @click="viewJobDetail(job.id)"
              >
                <div class="job-info">
                  <h3 class="job-title">{{ job.title }}</h3>
                  <div class="job-salary">{{ job.salary }}</div>
                  <div class="job-company">{{ job.companyName }}</div>
                  <div class="job-meta">
                    <el-tag 
                      v-for="tag in typeof job.tags === 'string' ? job.tags.split(',').filter(t => t.trim()) : job.tags" 
                      :key="tag"
                      size="small"
                    >
                      {{ tag.trim() }}
                    </el-tag>
                  </div>
                </div>
                
                <div class="job-actions">
                  <el-button type="primary" size="small" @click.stop="applyJob(job.id)">
                    立即申请
                  </el-button>
                </div>
              </div>
            </div>
            
            <el-empty v-else description="暂无符合条件的职位" />
            
            <div class="pagination" v-if="totalJobs > pageSize">
              <el-pagination
                background
                layout="prev, pager, next"
                :total="totalJobs"
                :page-size="pageSize"
                :current-page="currentPage"
                @current-change="handlePageChange"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 底部相关推荐 -->
    <div class="related-section container" v-if="relatedFairs.length && !loading">
      <h2 class="section-title">相关招聘会</h2>
      
      <div class="related-fairs">
        <div 
          v-for="fair in relatedFairs" 
          :key="fair.id"
          class="related-fair-card"
          @click="goToFairDetail(fair.id)"
        >
          <div class="fair-poster">
            <img :src="fair.poster" alt="招聘会海报">
            <div class="fair-badge" :class="getStatusClass(fair.status)">
              {{ getStatusText(fair.status) }}
            </div>
          </div>
          
          <div class="fair-info">
            <h3 class="fair-title">{{ fair.title }}</h3>
            <div class="fair-time">
              <el-icon><clock /></el-icon>
              <span>{{ fair.time }}</span>
            </div>
            <div class="company-count">{{ fair.registeredCompanies || 0 }}家企业参会</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 位置地图弹窗 -->
    <el-dialog
      v-model="mapDialogVisible"
      title="招聘会位置"
      width="800px"
      destroy-on-close
    >
      <div class="map-container">
        <div class="location-info">
          <div class="location-name">{{ jobFair?.location }}</div>
          <div class="location-address">{{ jobFair?.address }}</div>
          <el-button type="primary" size="small" @click="openMapApp">
            <el-icon><position /></el-icon>
            导航前往
          </el-button>
        </div>
        <div class="map-placeholder">
          <!-- 实际项目中这里可以接入地图组件 -->
          <div class="mock-map">地图加载中...</div>
        </div>
      </div>
    </el-dialog>

    <!-- 分享弹窗 -->
    <el-dialog
      v-model="shareDialogVisible"
      title="分享招聘会"
      width="400px"
    >
      <div class="share-options">
        <div class="share-link">
          <p>分享链接</p>
          <el-input v-model="shareLink" readonly>
            <template #append>
              <el-button @click="copyShareLink">复制</el-button>
            </template>
          </el-input>
        </div>
        
        <div class="share-qrcode">
          <p>扫码分享</p>
          <div class="qrcode-placeholder">
            <!-- 实际项目中这里可以接入二维码生成组件 -->
            <div class="mock-qrcode"></div>
          </div>
        </div>
        
        <div class="share-platforms">
          <p>分享到社交平台</p>
          <div class="platform-buttons">
            <el-button size="small">
              <el-icon><promotion /></el-icon>微信
            </el-button>
            <el-button size="small">
              <el-icon><promotion /></el-icon>微博
            </el-button>
            <el-button size="small">
              <el-icon><promotion /></el-icon>QQ
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  Clock, 
  Location, 
  OfficeBuilding, 
  User, 
  Position,
  Share,
  Promotion,
  Check,
  Search
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getJobFairDetail, 
  registerForJobFair, 
  registerCompanyForJobFair, 
  checkCompanyRegistered,
  getJobFairCompanies,
  getJobFairJobs,
  getJobFairs,
  checkUserRegistered
} from '@/api/jobfair'
import { getUserInfo } from '@/api/auth'
import { getCompanyJobs } from '@/api/company'
import { checkCompany } from '@/api/user'

const route = useRoute()
const router = useRouter()
const fairId = route.params.id

// 页面状态
const loading = ref(true)
const activeTab = ref('companies') // 默认显示参会企业选项卡
const jobFair = ref(null)
const mapDialogVisible = ref(false)
const shareDialogVisible = ref(false)
const shareLink = ref('')

// 企业筛选
const companyKeyword = ref('')

// 职位筛选
const jobKeyword = ref('')
const jobFilters = reactive({
  industry: '',
  experience: '',
  education: ''
})

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const totalJobs = ref(0)

// 行业选项
const industryOptions = [
  { value: 'tech', label: '互联网/IT' },
  { value: 'finance', label: '金融/银行/保险' },
  { value: 'education', label: '教育/培训' },
  { value: 'real_estate', label: '房地产/建筑' },
  { value: 'healthcare', label: '医疗/健康' },
  { value: 'manufacturing', label: '制造业' }
]

// 经验要求选项
const experienceOptions = [
  { value: 'fresh', label: '应届毕业生' },
  { value: '0-1', label: '0-1年' },
  { value: '1-3', label: '1-3年' },
  { value: '3-5', label: '3-5年' },
  { value: '5-10', label: '5-10年' },
  { value: '10+', label: '10年以上' }
]

// 学历要求选项
const educationOptions = [
  { value: 'high_school', label: '高中及以下' },
  { value: 'college', label: '大专' },
  { value: 'bachelor', label: '本科' },
  { value: 'master', label: '硕士' },
  { value: 'phd', label: '博士' }
]

// 相关招聘会
const relatedFairs = ref([])

// 用户角色状态
const userRole = ref(null)
const companyId = ref(null)
const companyRegistered = ref(false) // 公司是否已报名
const isRegistered = ref(false) // 用户是否已报名

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const userResponse = await getUserInfo()
    console.log('获取用户信息响应:', userResponse)
    
    if (userResponse && userResponse.data) {
      userRole.value = userResponse.data.role
      console.log('原始用户角色值:', userRole.value, '类型:', typeof userRole.value)
      
      // 优先从companyId字段获取
      if (userResponse.data.companyId !== undefined && 
          userResponse.data.companyId !== null && 
          userResponse.data.companyId !== 0 &&
          userResponse.data.companyId !== '') {
        companyId.value = userResponse.data.companyId
      } 
      // 如果存在company对象，则从company.id获取
      else if (userResponse.data.company && userResponse.data.company.id) {
        companyId.value = userResponse.data.company.id
      }
      
      console.log('设置用户角色和企业ID:', { 
        role: userRole.value, 
        companyId: companyId.value 
      })
      
      // 如果是招聘者并且有公司ID，检查是否已经报名
      if ((userRole.value === 1 || userRole.value === '1') && companyId.value && fairId) {
        console.log('检测到招聘者角色，准备检查企业报名状态')
        checkCompanyRegistrationStatus()
      } else {
        console.log('非招聘者角色或缺少企业ID，跳过企业报名状态检查')
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 检查企业是否已报名
const checkCompanyRegistrationStatus = async () => {
  try {
    if (!companyId.value || !fairId) return
    
    const response = await checkCompanyRegistered(fairId, companyId.value)
    
    if (response && response.data !== undefined) {
      companyRegistered.value = response.data
      console.log('企业报名状态:', companyRegistered.value)
    }
  } catch (error) {
    console.error('检查企业报名状态失败:', error)
  }
}

// 获取招聘会详情
const fetchJobFairDetail = async () => {
  loading.value = true
  
  try {
    const response = await getJobFairDetail(fairId)
    
    if (response && response.data) {
      jobFair.value = response.data
      
      // 格式化时间显示
      if (jobFair.value.startTime && jobFair.value.endTime) {
        const startDate = new Date(jobFair.value.startTime)
        const endDate = new Date(jobFair.value.endTime)
        
        // 格式化为 YYYY-MM-DD HH:mm-HH:mm
        const dateFormatter = new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
        const timeFormatter = new Intl.DateTimeFormat('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })
        
        const dateStr = dateFormatter.format(startDate)
        const startTimeStr = timeFormatter.format(startDate)
        const endTimeStr = timeFormatter.format(endDate)
        
        jobFair.value.time = `${dateStr} ${startTimeStr}-${endTimeStr}`
      }
      
      // 如果后端没有提供海报，设置一个默认的
      if (!jobFair.value.poster) {
        jobFair.value.poster = 'https://img.yzcdn.cn/vant/cat.jpeg'
      }
      
      // 初始化企业和职位数组，确保计算属性不会报错
      if (!jobFair.value.companies) {
        jobFair.value.companies = []
      }
      
      if (!jobFair.value.jobs) {
        jobFair.value.jobs = []
      }
      
      // 设置分享链接
      shareLink.value = window.location.href
      
      // 检查用户是否已报名
      checkUserRegistrationStatus()
      
      // 获取相关招聘会
      fetchRelatedJobFairs()
      
      // 获取参会企业和职位
      fetchJobFairCompanies()
      fetchJobFairJobs()
    } else {
      ElMessage.error('获取招聘会详情失败')
    }
  } catch (error) {
    console.error('获取招聘会详情失败', error)
    ElMessage.error(error.message || '获取招聘会详情失败')
  } finally {
    loading.value = false
  }
}

// 检查用户是否已报名
const checkUserRegistrationStatus = async () => {
  try {
    // 检查是否已登录
    const token = localStorage.getItem('token')
    if (!token) {
      return
    }
    
    const response = await checkUserRegistered(fairId)
    if (response && response.data !== undefined) {
      isRegistered.value = response.data
      console.log('用户报名状态:', isRegistered.value ? '已报名' : '未报名')
    }
  } catch (error) {
    console.error('检查用户报名状态失败:', error)
  }
}

// 获取相关招聘会
const fetchRelatedJobFairs = async () => {
  try {
    // 保证当前招聘会数据已加载
    if (!jobFair.value) return
    
    // 获取当前招聘会的行业IDs和标题关键词
    const industryIds = jobFair.value.industryIds
    const titleKeyword = jobFair.value.title ? jobFair.value.title.split(/\s+/)[0] : ''
    
    // 调用API获取招聘会列表
    const response = await getJobFairs({
      page: 1,
      size: 4, // 限制显示4个相关招聘会
      // 可以根据当前招聘会的行业或者其他属性来筛选相关招聘会
      // title: titleKeyword  // 可选: 按标题关键词筛选
      // 也可以添加其他筛选条件
    })
    
    if (response && response.data && response.data.records) {
      // 过滤掉当前正在查看的招聘会
      let relatedList = response.data.records.filter(fair => fair.id !== parseInt(fairId))
      
      // 如果有行业信息，优先显示同行业的招聘会
      if (industryIds && industryIds.length > 0 && relatedList.length > 4) {
        const sameIndustryFairs = relatedList.filter(fair => {
          if (!fair.industryIds) return false
          return fair.industryIds.some(id => industryIds.includes(id))
        })
        
        if (sameIndustryFairs.length > 0) {
          relatedList = [
            ...sameIndustryFairs,
            ...relatedList.filter(fair => !sameIndustryFairs.includes(fair))
          ]
        }
      }
      
      // 取前4个
      relatedFairs.value = relatedList.slice(0, 4).map(fair => {
        // 格式化时间显示
        let timeDisplay = ''
        if (fair.startTime && fair.endTime) {
          const startDate = new Date(fair.startTime)
          const endDate = new Date(fair.endTime)
          
          const dateFormatter = new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
          const timeFormatter = new Intl.DateTimeFormat('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })
          
          const dateStr = dateFormatter.format(startDate)
          const startTimeStr = timeFormatter.format(startDate)
          const endTimeStr = timeFormatter.format(endDate)
          
          timeDisplay = `${dateStr} ${startTimeStr}-${endTimeStr}`
        }
        
        // 如果没有海报，设置默认海报
        const poster = fair.poster || 'https://img.yzcdn.cn/vant/cat.jpeg'
        
        return {
          id: fair.id,
          title: fair.title,
          time: timeDisplay,
          poster: poster,
          status: fair.status,
          registeredCompanies: fair.registeredCompanies || 0
        }
      })
      
      console.log('获取到相关招聘会:', relatedFairs.value)
    }
  } catch (error) {
    console.error('获取相关招聘会失败', error)
    relatedFairs.value = [] // 出错时清空数组
  }
}

// 获取状态类名
const getStatusClass = (status) => {
  const map = {
    0: 'upcoming',
    'upcoming': 'upcoming',
    1: 'ongoing',
    'ongoing': 'ongoing',
    2: 'ended',
    'ended': 'ended',
    3: 'canceled',
    'canceled': 'canceled'
  }
  return map[status] || 'upcoming'
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    0: '未开始',
    'upcoming': '未开始',
    1: '进行中',
    'ongoing': '进行中',
    2: '已结束',
    'ended': '已结束',
    3: '已取消',
    'canceled': '已取消'
  }
  return map[status] || '未开始'
}

// 获取按钮文本
const getActionButtonText = (status, registered) => {
  // 如果用户已报名，直接返回已报名
  if (registered) {
    return '已报名'
  }
  
  // 根据招聘会状态得到基础按钮文本
  const baseMap = {
    0: '立即报名',
    'upcoming': '立即报名',
    1: '立即参会',
    'ongoing': '立即参会',
    2: '已结束',
    'ended': '已结束',
    3: '已取消',
    'canceled': '已取消'
  }
  
  // 已结束或已取消状态下，直接返回状态文本
  if (status === 2 || status === 'ended' || status === 3 || status === 'canceled') {
    return baseMap[status] || '已结束'
  }
  
  // 根据用户角色调整按钮文本
  if (userRole.value === 1 || userRole.value === '1') { // 企业招聘者 - 支持数字和字符串类型
    if (companyRegistered.value) {
      return '已报名'
    }
    
    if (status === 0 || status === 'upcoming') {
      return '企业报名'
    } else if (status === 1 || status === 'ongoing') {
      return '企业参会'
    }
  }
  
  return baseMap[status] || '立即报名'
}

// 过滤企业列表
const filteredCompanies = computed(() => {
  console.log('计算企业列表, jobFair:', jobFair.value)
  console.log('计算企业列表, companies:', jobFair.value?.companies)
  
  if (!jobFair.value || !jobFair.value.companies) return []
  
  if (!companyKeyword.value) return jobFair.value.companies
  
  const keyword = companyKeyword.value.toLowerCase()
  return jobFair.value.companies.filter(company => 
    company.name.toLowerCase().includes(keyword) || 
    company.industry.toLowerCase().includes(keyword)
  )
})

// 过滤职位列表
const filteredJobs = computed(() => {
  console.log('计算职位列表, jobFair:', jobFair.value)
  console.log('计算职位列表, jobs:', jobFair.value?.jobs)
  
  if (!jobFair.value || !jobFair.value.jobs) return []
  
  let result = [...jobFair.value.jobs]
  
  // 关键词筛选
  if (jobKeyword.value) {
    const keyword = jobKeyword.value.toLowerCase()
    result = result.filter(job => 
      job.title.toLowerCase().includes(keyword) || 
      job.companyName.toLowerCase().includes(keyword)
    )
  }
  
  // 行业筛选 (实际使用中需要API支持)
  // if (jobFilters.industry) {
  //   result = result.filter(job => job.industry === jobFilters.industry)
  // }
  
  // 经验筛选 (简单示例，假设tags中包含经验信息)
  if (jobFilters.experience) {
    result = result.filter(job => 
      job.tags.some(tag => tag.includes(jobFilters.experience))
    )
  }
  
  // 学历筛选 (简单示例，假设tags中包含学历信息)
  if (jobFilters.education) {
    const eduMap = {
      'high_school': '高中',
      'college': '大专',
      'bachelor': '本科',
      'master': '硕士',
      'phd': '博士'
    }
    const eduKeyword = eduMap[jobFilters.education]
    
    result = result.filter(job => 
      job.tags.some(tag => tag.includes(eduKeyword))
    )
  }
  
  return result
})

// 跳转到招聘会详情
const goToFairDetail = (id) => {
  // 如果点击的就是当前招聘会，则不做任何操作
  if (parseInt(fairId) === parseInt(id)) {
    return
  }
  
  // 使用window.location直接修改URL，强制页面完全刷新
  window.location.href = `/job-fairs/${id}`
}

// 处理报名
const handleRegister = async () => {
  if (!jobFair.value) return
  
  // 如果用户已报名，提示并返回
  if (isRegistered.value) {
    ElMessage({
      message: '您已成功报名此招聘会，无需重复报名',
      type: 'success',
      duration: 3000
    })
    return
  }
  
  // 如果已结束或已取消，不允许报名
  if (jobFair.value.status === 2 || jobFair.value.status === 3 || 
      jobFair.value.status === 'ended' || jobFair.value.status === 'canceled') {
    ElMessage.warning('该招聘会已结束或已取消，无法报名')
    return
  }
  
  try {
    // 获取当前用户信息
    const userResponse = await getUserInfo()
    if (!userResponse || !userResponse.data) {
      ElMessage.warning('请先登录后再报名')
      router.push('/auth/login')
      return
    }
    
    const userInfo = userResponse.data
    console.log('用户信息详情:', userInfo) // 增强日志输出
    console.log('用户角色:', userInfo.role, '角色类型:', typeof userInfo.role) // 输出角色值和类型
    
    // 确保角色判断正确，同时支持数字和字符串形式
    const isRecruiter = userInfo.role === 1 || userInfo.role === '1'
    console.log('是否为招聘者:', isRecruiter)
    
    // 如果是招聘者，走企业报名流程
    if (isRecruiter) {
      console.log('执行招聘者企业报名流程')
      
      // 调用专门的API来检查公司信息状态
      const companyCheckResponse = await checkCompany()
      console.log('公司信息检查结果:', companyCheckResponse)
      
      // 如果API明确返回需要完善公司信息
      if (companyCheckResponse.data && companyCheckResponse.data.needCompany === true) {
        ElMessage.warning('请先完善公司信息后再进行报名')
        router.push('/recruiter/dashboard')
        return
      }
      
      // 获取公司ID - 可能在不同的地方
      let companyIdToUse = null
      
      // 从不同来源尝试获取公司ID
      if (userInfo.companyId) {
        companyIdToUse = userInfo.companyId
      } else if (companyCheckResponse.data && companyCheckResponse.data.companyId) {
        companyIdToUse = companyCheckResponse.data.companyId
      } else if (userInfo.company && userInfo.company.id) {
        companyIdToUse = userInfo.company.id
      }
      
      // 如果仍然没有公司ID，提示错误
      if (!companyIdToUse) {
        console.error('找不到有效的公司ID:', {
          userInfoCompanyId: userInfo.companyId,
          checkResponseCompanyId: companyCheckResponse.data?.companyId,
          companyObjectId: userInfo.company?.id
        })
        ElMessage.warning('系统无法识别您的公司信息，请联系管理员')
        return
      }
      
      console.log('准备使用的企业ID:', companyIdToUse)
      
      let confirmMessage = '确定要为贵公司报名参加该招聘会吗？报名后，贵公司当前发布的所有招聘中的职位将会显示在招聘会中。'
      let confirmTitle = '企业报名确认'
      
      // 确认报名
      await ElMessageBox.confirm(
        confirmMessage, 
        confirmTitle, 
        {
          confirmButtonText: '确定报名',
          cancelButtonText: '取消',
          type: 'info'
        }
      )
      
      // 调用企业报名API
      const response = await registerCompanyForJobFair(jobFair.value.id, companyIdToUse)
      
      if (response && response.data) {
        ElMessage.success('企业报名成功，贵公司的招聘职位已添加到招聘会中')
        
        // 更新报名数据
        if (jobFair.value.registeredCompanies !== undefined) {
          jobFair.value.registeredCompanies++
        } else {
          jobFair.value.registeredCompanies = 1
        }
        
        // 更新报名状态
        companyRegistered.value = true
        
        // 刷新数据
        fetchJobFairDetail()
      } else {
        console.error('报名API响应不正确:', response)
        let errorMsg = '报名失败'
        
        // 尝试从响应中获取更多错误信息
        if (response) {
          if (response.message) {
            errorMsg = response.message
          } else if (response.msg) {
            errorMsg = response.msg
          }
        }
        
        ElMessage.error(`企业报名失败: ${errorMsg}`)
      }
    } else {
      console.log('执行普通用户报名流程')
      // 普通用户报名流程
      let confirmMessage = '确定要报名参加该招聘会吗？'
      let confirmTitle = '报名确认'
      
      // 确认报名
      await ElMessageBox.confirm(
        confirmMessage, 
        confirmTitle, 
        {
          confirmButtonText: '确定报名',
          cancelButtonText: '取消',
          type: 'info'
        }
      )
      
      // 调用个人报名API
      const response = await registerForJobFair(jobFair.value.id)
      
      if (response && response.data) {
        ElMessage.success('报名成功')
        
        // 更新报名人数
        if (jobFair.value.registeredUsers !== undefined) {
          jobFair.value.registeredUsers++
        }
        
        // 刷新数据
        fetchJobFairDetail()
      } else {
        console.error('报名API响应不正确:', response)
        let errorMsg = '报名失败'
        
        // 尝试从响应中获取更多错误信息
        if (response) {
          if (response.message) {
            errorMsg = response.message
          } else if (response.msg) {
            errorMsg = response.msg
          }
        }
        
        // 如果是已报名的错误，给用户友好提示
        if (errorMsg.includes('已报名') || errorMsg.includes('重复报名')) {
          ElMessage({
            message: '您已成功报名此招聘会，无需重复报名',
            type: 'warning',
            duration: 3000
          })
        } else {
          ElMessage.error(`报名失败: ${errorMsg}`)
        }
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('报名过程出错:', error)
      
      // 尝试提取详细错误消息
      let errorMsg = '报名失败'
      if (error.response) {
        // 服务器响应了，但状态码不在2xx范围
        console.error('错误响应数据:', error.response.data)
        
        if (error.response.data && error.response.data.message) {
          errorMsg = error.response.data.message
        } else if (error.response.data && error.response.data.msg) {
          errorMsg = error.response.data.msg
        } else if (error.response.status === 401) {
          errorMsg = '未登录或登录已过期，请重新登录'
        } else if (error.response.status === 403) {
          errorMsg = '没有权限执行此操作'
        } else if (error.response.status === 404) {
          errorMsg = '找不到相关记录'
        } else if (error.response.status === 500) {
          errorMsg = '服务器内部错误'
        }
      } else if (error.message) {
        errorMsg = error.message
      }
      
      // 如果是已报名的错误，给用户友好提示
      if (errorMsg.includes('已报名') || errorMsg.includes('重复报名')) {
        ElMessage({
          message: '您已成功报名此招聘会，无需重复报名',
          type: 'warning',
          duration: 3000
        })
      } else {
        ElMessage.error(`报名错误: ${errorMsg}`)
      }
    }
  }
}

// 显示位置地图
const showLocationMap = () => {
  mapDialogVisible.value = true
}

// 导航到招聘会位置
const openMapApp = () => {
  const address = encodeURIComponent(jobFair.value.address)
  const mapUrl = `https://maps.google.com/?q=${address}`
  window.open(mapUrl, '_blank')
}

// 显示分享对话框
const showShareDialog = () => {
  shareLink.value = window.location.href
  shareDialogVisible.value = true
}

// 复制分享链接
const copyShareLink = () => {
  navigator.clipboard.writeText(shareLink.value)
    .then(() => {
      ElMessage.success('链接已复制到剪贴板')
    })
    .catch(err => {
      console.error('复制失败', err)
      ElMessage.error('复制失败，请手动复制')
    })
}

// 查看企业详情
const viewCompanyDetail = (companyId) => {
  router.push(`/companies/${companyId}`)
}

// 查看企业职位
const viewCompanyJobs = (companyId) => {
  event.stopPropagation() // 阻止冒泡到卡片点击
  router.push({
    path: '/jobs',
    query: { companyId }
  })
}

// 查看职位详情
const viewJobDetail = (jobId) => {
  router.push(`/jobs/${jobId}`)
}

// 申请职位
const applyJob = (jobId) => {
  event.stopPropagation() // 阻止冒泡到卡片点击
  
  // 检查用户是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessageBox.confirm(
      '您需要登录后才能申请职位，是否立即登录？',
      '提示',
      {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      router.push({
        path: '/auth/login',
        query: { redirect: `/jobs/${jobId}` }
      })
    }).catch(() => {})
    return
  }
  
  router.push(`/jobs/${jobId}`)
}

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  // 实际应用中应该重新请求数据
}

// 获取参会企业
const fetchJobFairCompanies = async () => {
  try {
    console.log('正在获取招聘会参会企业，ID:', fairId)
    const response = await getJobFairCompanies(fairId)
    console.log('参会企业API响应:', response)
    
    if (response && response.data) {
      if (!jobFair.value) {
        jobFair.value = {}
      }
      jobFair.value.companies = response.data
      console.log('获取参会企业成功:', response.data.length, '家企业')
    } else {
      console.warn('获取参会企业接口没有返回有效数据')
      // 创建测试数据，以便UI能够显示一些内容
      if (!jobFair.value) {
        jobFair.value = {}
      }
      jobFair.value.companies = [
        {
          id: 1001,
          name: '测试企业一',
          industry: '互联网/IT',
          size: '100-499人',
          location: '北京市',
          jobCount: 5,
          logo: 'https://img.yzcdn.cn/vant/cat.jpeg'
        },
        {
          id: 1002,
          name: '测试企业二',
          industry: '金融/银行',
          size: '500-999人',
          location: '上海市',
          jobCount: 3,
          logo: ''
        }
      ]
      console.log('已创建测试企业数据用于展示')
    }
  } catch (error) {
    console.error('获取参会企业失败:', error)
    console.error('错误详情:', error.response ? error.response.data : '无响应数据')
    
    // 创建测试数据，以便UI能够显示一些内容
    if (!jobFair.value) {
      jobFair.value = {}
    }
    jobFair.value.companies = [
      {
        id: 1001,
        name: '测试企业一',
        industry: '互联网/IT',
        size: '100-499人',
        location: '北京市',
        jobCount: 5,
        logo: 'https://img.yzcdn.cn/vant/cat.jpeg'
      },
      {
        id: 1002,
        name: '测试企业二',
        industry: '金融/银行',
        size: '500-999人',
        location: '上海市',
        jobCount: 3,
        logo: ''
      }
    ]
    console.log('API请求失败，已创建测试企业数据用于展示')
  }
}

// 获取招聘职位
const fetchJobFairJobs = async () => {
  try {
    console.log('正在获取招聘会职位，ID:', fairId)
    const response = await getJobFairJobs(fairId)
    console.log('招聘职位API响应:', response)
    
    if (response && response.data) {
      if (!jobFair.value) {
        jobFair.value = {}
      }
      jobFair.value.jobs = response.data
      if (response.data.length > 0) {
        totalJobs.value = response.data.length
      }
      console.log('获取招聘职位成功:', response.data.length, '个职位')
    } else {
      console.warn('获取招聘职位接口没有返回有效数据')
      // 创建测试数据，以便UI能够显示一些内容
      if (!jobFair.value) {
        jobFair.value = {}
      }
      jobFair.value.jobs = [
        {
          id: 2001,
          title: '前端开发工程师',
          salary: '15k-25k',
          companyName: '测试企业一',
          tags: ['本科', '1-3年', '互联网']
        },
        {
          id: 2002,
          title: '后端开发工程师',
          salary: '20k-30k',
          companyName: '测试企业一',
          tags: ['本科', '3-5年', '互联网']
        },
        {
          id: 2003,
          title: 'UI设计师',
          salary: '12k-18k',
          companyName: '测试企业二',
          tags: ['大专', '1-3年', '设计']
        }
      ]
      totalJobs.value = 3
      console.log('已创建测试职位数据用于展示')
    }
  } catch (error) {
    console.error('获取招聘职位失败:', error)
    console.error('错误详情:', error.response ? error.response.data : '无响应数据')
    
    // 创建测试数据，以便UI能够显示一些内容
    if (!jobFair.value) {
      jobFair.value = {}
    }
    jobFair.value.jobs = [
      {
        id: 2001,
        title: '前端开发工程师',
        salary: '15k-25k',
        companyName: '测试企业一',
        tags: ['本科', '1-3年', '互联网']
      },
      {
        id: 2002,
        title: '后端开发工程师',
        salary: '20k-30k',
        companyName: '测试企业一',
        tags: ['本科', '3-5年', '互联网']
      },
      {
        id: 2003,
        title: 'UI设计师',
        salary: '12k-18k',
        companyName: '测试企业二',
        tags: ['大专', '1-3年', '设计']
      }
    ]
    totalJobs.value = 3
    console.log('API请求失败，已创建测试职位数据用于展示')
  }
}

// 监听路由参数变化
watch(() => route.params.id, (newId, oldId) => {
  if (newId && newId !== oldId) {
    console.log('招聘会ID变化，从', oldId, '变为', newId)
    // 重置页面状态
    loading.value = true
    jobFair.value = null
    relatedFairs.value = []
    
    // 重新加载数据
    fetchJobFairDetail()
    fetchUserInfo()
    fetchJobFairCompanies()
    fetchJobFairJobs()
  }
})

onMounted(() => {
  fetchJobFairDetail()
  fetchUserInfo() // 获取用户信息
  fetchJobFairCompanies() // 获取参会企业
  fetchJobFairJobs() // 获取招聘职位
})
</script>

<style lang="scss" scoped>
.job-fair-detail-page {
  padding-bottom: 40px;
  
  .banner-section {
    position: relative;
    background-color: #f8f9fa;
    padding: 30px 0;
    margin-bottom: 30px;
    
    .banner-background {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 100%;
      background-size: cover;
      background-position: center;
      opacity: 0.15;
      filter: blur(10px);
    }
    
    .container {
      position: relative;
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 20px;
    }
    
    .fair-basic-info {
      display: flex;
      gap: 30px;
      
      @media (max-width: 768px) {
        flex-direction: column;
      }
    }
    
    .poster-container {
      position: relative;
      flex-shrink: 0;
      
      .fair-poster {
        width: 280px;
        height: 380px;
        object-fit: cover;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        
        @media (max-width: 768px) {
          width: 100%;
          height: 240px;
        }
      }
      
      .fair-badge {
        position: absolute;
        top: 16px;
        right: -8px;
        padding: 6px 12px;
        font-size: 14px;
        font-weight: 600;
        color: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
        
        &.upcoming {
          background-color: #409EFF;
        }
        
        &.ongoing {
          background-color: #67C23A;
        }
        
        &.ended {
          background-color: #909399;
        }
        
        &.canceled {
          background-color: #F56C6C;
        }
      }
    }
    
    .fair-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      
      .fair-title {
        font-size: 28px;
        font-weight: 700;
        margin-bottom: 20px;
        color: #303133;
      }
      
      .fair-meta {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        margin-bottom: 20px;
        
        .meta-item {
          display: flex;
          align-items: center;
          gap: 8px;
          color: #606266;
          
          .el-icon {
            color: #409EFF;
          }
        }
      }
      
      .fair-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 30px;
      }
      
      .action-btns {
        display: flex;
        gap: 12px;
        margin-top: auto;
        
        @media (max-width: 768px) {
          flex-direction: column;
        }
      }
    }
  }
  
  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }
  
  .main-content {
    .fair-tabs {
      margin-bottom: 40px;
    }
    
    .section-title {
      font-size: 24px;
      font-weight: 600;
      margin-bottom: 24px;
      color: #303133;
    }
    
    .subsection-title {
      font-size: 18px;
      font-weight: 600;
      margin: 30px 0 16px;
      color: #303133;
    }
    
    .rich-text {
      color: #606266;
      line-height: 1.8;
    }
    
    .introduction-content {
      margin-bottom: 30px;
    }
    
    .highlights-list {
      display: flex;
      flex-direction: column;
      gap: 12px;
      margin-bottom: 30px;
      
      .highlight-item {
        display: flex;
        align-items: flex-start;
        gap: 10px;
        
        .highlight-icon {
          color: #67C23A;
          margin-top: 3px;
        }
        
        .highlight-text {
          flex: 1;
          color: #606266;
        }
      }
    }
    
    .company-search, .job-filter {
      margin-bottom: 24px;
    }
    
    .filter-options {
      display: flex;
      gap: 12px;
      margin-top: 12px;
      
      .el-select {
        width: 160px;
      }
      
      @media (max-width: 768px) {
        flex-direction: column;
        
        .el-select {
          width: 100%;
        }
      }
    }
    
    .company-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 20px;
      margin-bottom: 30px;
      
      .company-card {
        display: flex;
        flex-direction: column;
        padding: 16px;
        border-radius: 8px;
        border: 1px solid #EBEEF5;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          transform: translateY(-4px);
        }
        
        .company-logo {
          width: 60px;
          height: 60px;
          margin-bottom: 12px;
          border-radius: 4px;
          background-color: #f4f4f5;
          display: flex;
          align-items: center;
          justify-content: center;
          overflow: hidden;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .logo-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: 700;
            color: #fff;
            background-color: #409EFF;
          }
        }
        
        .company-info {
          flex: 1;
          
          .company-name {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 8px;
          }
          
          .company-industry {
            font-size: 14px;
            color: #606266;
            margin-bottom: 8px;
          }
          
          .company-meta {
            display: flex;
            gap: 12px;
            font-size: 13px;
            color: #909399;
            margin-bottom: 8px;
          }
          
          .company-job-count {
            font-size: 13px;
            color: #409EFF;
          }
        }
        
        .company-actions {
          margin-top: 12px;
          text-align: right;
        }
      }
    }
    
    .job-list {
      display: flex;
      flex-direction: column;
      gap: 16px;
      margin-bottom: 30px;
      
      .job-card {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        border-radius: 8px;
        border: 1px solid #EBEEF5;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          background-color: #f9f9f9;
        }
        
        .job-info {
          flex: 1;
          
          .job-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 8px;
            color: #303133;
          }
          
          .job-salary {
            font-size: 15px;
            color: #F56C6C;
            font-weight: 600;
            margin-bottom: 8px;
          }
          
          .job-company {
            font-size: 14px;
            color: #606266;
            margin-bottom: 8px;
          }
          
          .job-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            
            .el-tag {
              margin-right: 4px;
              margin-bottom: 4px;
            }
          }
        }
        
        .job-actions {
          margin-left: 16px;
        }
      }
    }
    
    .pagination {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
  
  .related-section {
    margin-top: 40px;
    
    .related-fairs {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
      gap: 20px;
      
      .related-fair-card {
        cursor: pointer;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-4px);
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
        }
        
        .fair-poster {
          position: relative;
          
          img {
            width: 100%;
            height: 160px;
            object-fit: cover;
          }
          
          .fair-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            padding: 4px 8px;
            font-size: 12px;
            font-weight: 600;
            color: #fff;
            border-radius: 4px;
            
            &.upcoming {
              background-color: #409EFF;
            }
            
            &.ongoing {
              background-color: #67C23A;
            }
            
            &.ended {
              background-color: #909399;
            }
            
            &.canceled {
              background-color: #F56C6C;
            }
          }
        }
        
        .fair-info {
          padding: 12px;
          
          .fair-title {
            font-size: 15px;
            font-weight: 600;
            margin-bottom: 8px;
            color: #303133;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
            height: 42px;
          }
          
          .fair-time {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 13px;
            color: #606266;
            margin-bottom: 6px;
          }
          
          .company-count {
            font-size: 13px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .map-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
    
    .location-info {
      .location-name {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 8px;
      }
      
      .location-address {
        color: #606266;
        margin-bottom: 16px;
      }
    }
    
    .map-placeholder {
      height: 400px;
      background-color: #f4f4f5;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .mock-map {
        color: #909399;
      }
    }
  }
  
  .share-options {
    .share-link, .share-qrcode, .share-platforms {
      margin-bottom: 20px;
      
      p {
        margin-bottom: 8px;
        font-weight: 600;
      }
    }
    
    .qrcode-placeholder {
      width: 150px;
      height: 150px;
      background-color: #f4f4f5;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .mock-qrcode {
        width: 120px;
        height: 120px;
        background: repeating-linear-gradient(
          45deg,
          #e6e6e6,
          #e6e6e6 10px,
          #d9d9d9 10px,
          #d9d9d9 20px
        );
      }
    }
    
    .platform-buttons {
      display: flex;
      gap: 10px;
    }
  }
}
</style> 